package com.data4.utils.service.impl;

import cn.hutool.core.lang.UUID;
import com.data4.feignapi.dto.Result;
import com.data4.utils.common.constants.OSSConstants;
import com.data4.utils.common.tools.MinioUtils;
import com.data4.utils.service.OSSService;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Service
@Slf4j
public class OSSServiceImpl implements OSSService {
    @Resource
    private MinioUtils minioUtils;

    @Override
    public Result uploadFile(String bucketName, MultipartFile file) {
        try {
            //文件名，这里我觉得可以使用时间戳和用户id进行命名
            String fileName = file.getOriginalFilename();
            String newFileName = System.currentTimeMillis() + UUID.fastUUID()
                    .toString().split("-")[0] + "." +
                    StringUtils.substringAfterLast(fileName, ".");
            //类型
            String contentType = file.getContentType();
            Map<String, Object> result = minioUtils
                    .uploadFileWithUrl(bucketName,
                            file, newFileName, contentType);
            String url = (String) result.get("url");
            return Result.ok(url);
        } catch (Exception e) {
            log.error(OSSConstants.UPLOAD_FAIL);
            return Result.fail(OSSConstants.UPLOAD_FAIL);
        }
    }

    @Override
    public Result deleteFile(String bucketName, String fileName) {
        boolean removeFile = minioUtils.removeFile(bucketName, fileName);
        return removeFile ? Result.ok(OSSConstants.DELETE_SUCCESS)
                : Result.fail(OSSConstants.DELETE_FAIL);
    }

    @Override
    public Result getFileInfo(String bucketName, String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String fileStatusInfo = minioUtils.getFileStatusInfo(bucketName, fileName);
        return Result.ok(fileStatusInfo);
    }

}
